<template>
    <el-main style="padding: 0px 20px">
      <el-row style="margin:20px 0px">
        <my-Search :searchOption="searchType" :searchWay="true"  @onSearch="getSearchContent"></my-Search>
        <my-Search :searchWay="true" :inputPlaceholder="'公告标题'" @onSearch="getTitleSearchContent"></my-Search>
        <el-select style="margin-right:10px;width:110px" v-model="choiceStatusType" placeholder="公告状态" @change="statusSearch"  clearable >
          <el-option
            v-for="(item,index) in statusType"
            :key="index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select style="margin-right:10px;width:110px" v-model="searchCondition.type" placeholder="公告类型" @change="getNoticeList"  clearable >
          <el-option
            v-for="(item,index) in noticeType"
            :key="index"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
        <el-date-picker
          v-model="choiceDateTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="发布开始日期"
          end-placeholder="发布结束日期"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @blur="choiceDate"
          @change="choiceDate"
          >
        </el-date-picker>
        <el-button :disabled="selectTableRowId.length<=1" v-if="hasPerm('msg:notice:deletebatch')" style="margin-left:10px;"
        type="danger" icon="el-icon-delete-solid" size="medium" @click="deleteNoticeBatch">批量删除</el-button>
      </el-row>
      <el-table
        @selection-change="selectTable"
        :height="tableHeight"
        :data="articelListDate"
        row-key="id"
        ref="articleTableRef"
        border
        stripe
      >
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column type="index" align="center" width="55" label="序号"></el-table-column>
        <el-table-column prop="title" align="center" label="公告标题" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" align="center" label="公告类型" width="160"></el-table-column>
        <el-table-column prop="username" align="center" label="发布人" width="180"></el-table-column>
        <el-table-column prop="sendTime" align="center" :label="showTimeLabel" width="200" sortable>
          <template slot-scope="scope">
            {{scope.row.status==1 ? scope.row.sendTime: scope.row.updateTime}}
          </template>
        </el-table-column>
        <el-table-column prop="count" align="center" label="浏览数" width="100" sortable></el-table-column >
        <el-table-column label="状态" align="center" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="草稿"
              inactive-text="发布"
              :active-value="0"
              :inactive-value="1"
              active-color="#ff4949"
              inactive-color="#13ce66"
              @change="editNoticeStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="240">
          <template slot-scope="scope">
            <el-button v-if="hasPerm('msg:notice:edit')&&scope.row.status==0" type="primary" icon="el-icon-edit" size="small" @click="editNotice(scope.row)" >编辑</el-button>
            <el-button v-if="hasPerm('msg:notice:list')&&scope.row.status==1" type="primary" icon="el-icon-view" size="small" @click="toNoticeInfo(scope.row)" >查看</el-button>
            <el-button v-if="hasPerm('msg:notice:delete')" type="danger" icon="el-icon-delete" size="small" @click="deleteNotice(scope.row)" >删除</el-button>
          </template>
        </el-table-column>


      </el-table>
      <!-- 分页区 -->
      <pagination
      ref="pagination"
      @pagination="getPagination"
      :total="parseInt(totalPage)"
      :page="parseInt(searchCondition.page)"
      :limit="parseInt(searchCondition.pageSize)"
      :pageSizes="paginationSize"
      ></pagination>
    </el-main>
</template>

<script>
import {
  getNoticeListApi,
  editNoticeStatusApi,
  deleteNoticeApi,
  deleteNoticeBatchApi,
  getNoticeTypeApi,
} from "@/api/notice"
import { deleteAllFilesApi } from "@/api/pictures";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
  export default {
    components: {  mySearch, pagination},
    data(){
      return{
        articelListDate:[],
        //被选中的行 携带Id
        selectTableRowId: [],
        //被选中的行 携带No
        selectTableRowNo: [],
        tableHeight:0,
        searchCondition :{
          uid:'',
          nid:'',
          username:'',
          title:'',
          type:'',
          status:'',
          orderField:0,
          startTime:'',
          endTime:'',
          page: 1,
          pageSize: 10,
        },
        //分页容量
        paginationSize: [5,10,30,50,100,200],
        choiceStatusType:[],
        noticeType:'',
        showTimeLabel:'发布/修改时间',
        statusType:[{label:"已发布",value:"1"},{label:"草稿",value:"0"}],
        //筛选项
        searchType:[{label:"学号/工号",value:"0"},{label:"姓名",value:"1"}],
        //查询返回 总记录数
        totalPage: 0,
        choiceDateTime:'',
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一周',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一个月',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近半年',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      }
    },
    created() {
      this.getNoticeType();
    },
    mounted() {
      this.$nextTick(() => {
        //有页码区就高度多-120
        this.tableHeight = window.innerHeight - 323 - 120;
      })
    },
    methods:{
      //
      editNotice(row){
        this.$router.push("/notice/edit/"+row.no);
      },
      //查看公告详情
      toNoticeInfo(row){
        this.$router.push(`/noticeinfo/0/${row.no}`);
      },
      //获取选择表格项
      selectTable(selection){
        this.selectTableRowId = [];
        this.selectTableRowNo = [];
        selection.forEach(item=>{
          this.selectTableRowId.push(item.id);
          this.selectTableRowNo.push(item.no);
        })
      },
      //批量删除
      async deleteNoticeBatch() {
        let confirm = await this.$myconfirm("此操作不可逆！确定删除这些公告吗？");
        if (confirm) {
          let deleteArray = this.selectTableRowId.toString();
          let deleteList = this.selectTableRowNo.toString();
          let res = await deleteNoticeBatchApi({ids:deleteArray});
          if(res && res.code == 200){
            if(this.totalPage % this.searchCondition.pageSize ==this.selectTableRowId.length){
              this.searchCondition.page-=1;
            }
            //删除封面及数据库图片信息（公告有封面所以要删除）
            await deleteAllFilesApi({bids: deleteList});
            this.getNoticeList();
            this.$message.success(res.msg);
          }
        }
      },
      //删除消息
      async deleteNotice(row){
        let confirm = await this.$myconfirm("确定删除该公告吗？");
        if (confirm) {
          let res = await deleteNoticeApi({id:row.id});
          if (res && res.code == 200) {
            // 检查最后一页是否只有一条数据
            if(this.searchCondition.pageSize ==1 || this.totalPage % this.searchCondition.pageSize ==1){
              this.searchCondition.page-=1;
            }
            // 删除封面及数据库图片信息（公告有封面所以要删除）
            await deleteAllFilesApi({bids: row.no});
            this.getNoticeList();
            this.$message.success(res.msg);
          }
        }
      },
      //修改消息状态
      async editNoticeStatus(row){
        let res = await editNoticeStatusApi(row)
        if(res&&res.code==200){
          row.version = res.data.version;
          row.status = res.data.status;
          this.$message.success(res.msg);
        }
      },
      //日期范围查询
      choiceDate(){
        if(this.choiceDateTime!=null){
          this.searchCondition.startTime = this.choiceDateTime[0];
          this.searchCondition.endTime = this.choiceDateTime[1];
        }else{
          this.searchCondition.startTime = '';
          this.searchCondition.endTime = '';
        }
        this.getNoticeList();
      },
      //状态查询
      statusSearch(){
        this.searchCondition.status = this.choiceStatusType;
        this.getNoticeList();
      },
      //标题查询
      getTitleSearchContent(val){
        this.searchCondition.title = val;
        this.getNoticeList();
      },
      //内容查询
      getSearchContent(val,type){
        switch (type) {
          case '0':
            this.searchCondition.nid = val;
            this.searchCondition.username = '';
            break;
          case '1':
            this.searchCondition.nid = '';
            this.searchCondition.username = val;
            break;
          default:
            this.searchCondition.no = '';
            this.searchCondition.nid = '';
            break;
        }
        this.getNoticeList();
      },
      //分页查询
      getPagination(val){
        this.searchCondition.page = val.page;
        this.searchCondition.pageSize = val.limit;
        this.getNoticeList();
      },
      //查询
      async getNoticeList(){
        let res = await getNoticeListApi(this.searchCondition)
        if(res&&res.code==200){
          this.totalPage = res.data.total;
          this.articelListDate = res.data.list;
        }
      },
      //获取公告类型
      async getNoticeType(){
        let res = await getNoticeTypeApi();
        if(res&&res.code==200){
          this.noticeType = res.data;
          this.getNoticeList();
        }
      },
    },
    computed:{

    },
    filters:{
    },
    watch:{
      choiceStatusType(val){
        if(val==1){
          this.showTimeLabel = '发布时间';
        }else if(val==0&&val!=''){
          this.showTimeLabel = '最后修改时间'
        }else{
          this.showTimeLabel = '发布/修改时间'
        }
      }

    }
  }
</script>

<style lang="scss" scoped>

</style>
